package com.a2j.web.car.service.impl;

import com.a2j.beans.base.BaseBean;
import com.a2j.beans.base.code.ResponseCode;
import com.a2j.beans.car.CarBrand;
import com.a2j.exception.BizException;
import com.a2j.web.car.mapper.CarBrandMapper;
import com.a2j.web.car.service.CarBrandService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author: bzb
 * Data: 2021/10/31 22:51
 * Desc: 品牌实现
 */
@Service
public class CarBrandImpl implements CarBrandService {

    @Resource
    CarBrandMapper mapper;

    @Override
    public void addCarBrand(CarBrand record) {
        // name不能为空
        Assert.notNull(record, "品牌对象为空!");
        Assert.hasLength(record.getName(), "品牌名称不能为空!");

        record.setId(null); // 主键置空

        // TODO: 2021/10/31 新建人和新建时间
        int result = mapper.addCarBrand(record);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_ADD);
        }
    }

    @Override
    public void deleteCarBrand(Integer id) {
        Assert.notNull(id, "品牌id为空!");

        int result = mapper.deleteCarBrand(id);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_DELETE);
        }
    }

    @Override
    public BaseBean<CarBrand> getCarBrandDetail(Integer id) {
        Assert.notNull(id, "品牌id为空!");

        CarBrand detail = mapper.getCarBrandDetail(id);
        if (detail == null) {
            throw new BizException(ResponseCode.NO_DATA);
        }

        return BaseBean.success(detail);
    }

    @Override
    public BaseBean<List<CarBrand>> getAllCarBrands() {
        List<CarBrand> allCarBrands = mapper.getAllCarBrands();
        if (allCarBrands == null) {
            throw new BizException(ResponseCode.NO_DATA);
        }

        return BaseBean.success(allCarBrands);
    }

    @Override
    public BaseBean<List<String>> getAllLetters() {
        List<String> allLetters = mapper.getAllLetters();

        if (allLetters.isEmpty()) {
            throw new BizException(ResponseCode.NO_DATA);
        }

        return BaseBean.success(allLetters);
    }

    @Override
    public void enable(Integer id, Integer enable) {
        Assert.notNull(id, "品牌id为空!");
        if (enable == null) enable = 0;

        CarBrand record = CarBrand
                .builder()
                .id(id)
                .enable(enable)
                .build();

        int result = mapper.updateCarBrand(record);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE);
        }
    }

    @Override
    public void updateCarBrand(CarBrand record) {
        Assert.notNull(record, "品牌对象为空!");
        Assert.notNull(record.getId(), "品牌id为空!");
//        Assert.hasLength(record.getName(), "品牌名称不能为空!");

        int result = mapper.updateCarBrand(record);
        if (result == 0) {
            throw new BizException(ResponseCode.FAILED_UPDATE);
        }
    }
}
